﻿using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Shinva.Variables.Interface;
using Shinva.Variables.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shell.ViewModels
{
     /// <summary>
     /// 变量表的视图模型，与业务模型进行绑定
     /// </summary>
    public class PlcVariableViewModel : ReactiveUI.ReactiveObject
    {
        [Reactive]
        public string Name { get; set; }
        [Reactive]
        public DataType DataType { get; set; }
        [Reactive]
        public string Address { get; set; }
        [Reactive]
        public string Description { get; set; }

        [Reactive]
        public string Value { get; set; }

        /// <summary>
        /// 动态集合，可以与前端关联
        /// </summary>
        public ObservableCollection<PlcVariableViewModel> Children { get; }
= new ObservableCollection<PlcVariableViewModel>();


        /// <summary>
        /// 此处需要递归添加子元素
        /// </summary>
        /// <param name="member"></param>
        public PlcVariableViewModel(IPlcMember member)
        {

            //InsertChild(member);
            Name = member.Name;
            DataType = member.DataType;
            Address = $"{member.Address.ByteOffset}.{member.Address.BitOffset}";
            // member.WhenAnyValue(x => x.Value).BindTo(this,x=>x.Value);
            member.WhenAnyValue(x => x.Value).BindTo(this, x => x.Value);
            // member.Value = "0";
            //seriportClient.WhenAnyValue(x => x.Connected).BindTo(this, x => x.isModBusOpen);

            if (member is PlcComplexBase pcb)
            {
                foreach (var child in pcb.GetMembers())
                {
                    Children.Add(new PlcVariableViewModel(child));
                }
            }
        }
    }
    }
